'use strict';

const _ = require('lodash')
const {Controller} = require('ee-core');
const path = require('path');
const fs = require('fs');
const ps = require("ee-core/ps");

class WallpaperController extends Controller {
  constructor(ctx) {
    super(ctx);
  }

  /**
   * 获取指定目录的绝对路径
   * @param dirname
   * @returns {string}
   */
  getRootPath(dirname) {
    return path.join(ps.getRootDir(), dirname)
  }

  /**
   * 所有方法接收两个参数
   * @param args 前端传的参数
   * @param event - ipc通信时才有值。invoke()方法时，event == IpcMainInvokeEvent; send()/sendSync()方法时，event == IpcMainEvent
   */
  /**
   * 检测http服务是否开启
   */
  async checkHttpServer() {
    const httpServerConfig = this.app.config.httpServer;
    const url = httpServerConfig.protocol + httpServerConfig.host + ':' + httpServerConfig.port;

    return {
      enable: httpServerConfig.enable,
      server: url
    };
  }

  /**
   * 是否存在目录files
   * @returns {boolean}
   */
  hasDirFiles() {
    return fs.existsSync(this.getRootPath('files'))
  }

  /**
   * 创建目录files
   */
  createDirFiles() {
    fs.mkdirSync(this.getRootPath('files'))
  }

  /**
   * 写入文件到指定目录
   * @param filename
   * @param filepath
   */
  writeFile2Dir(filename, filepath) {
    fs.writeFileSync(path.join(this.getRootPath('files'), filename), fs.readFileSync(filepath))
  }

  /**
   * 上传文件
   * @returns {Promise<{success: boolean, message}|{success: boolean, message: string}>}
   */
  async uploadFile() {
    const files = this.app.request.files;
    const file = files.file;

    try {
      // 检测是否存在files目录，不存在则创建目录
      if (!this.hasDirFiles()) this.createDirFiles()

      if (_.isArray(file)) {
        file.forEach(item => {
          this.writeFile2Dir(item.originalFilename, item.filepath)
        })
      } else {
        this.writeFile2Dir(file.originalFilename, file.filepath)
      }
    } catch (e) {
      return {success: false, message: e.message}
    }
    return {success: true, message: `The file ${file.originalFilename} has been saved!`}
  }

  /**
   * 查询文件
   * @returns {Promise<void>}
   */
  async getFiles() {
    // 判断是否存在文件目录
    if (!this.hasDirFiles()) {
      return {success: true, list: [], message: '暂无数据!'}
    }
    // 读取文件目录下的文件名称
    const dirPath = this.getRootPath('files')
    const filesPathList = fs.readdirSync(dirPath, 'utf8')

    console.log('filesPathList', filesPathList);

    // 读取每个文件的内容
    _.forEach(filesPathList, filename => {
      fs.readFile(`${dirPath}/${filename}`, 'utf-8', (err, data) => {
        if (err) throw err
        // todo: key-value方式组装文件内容并返回
      })
    })
  }
}

WallpaperController.toString = () => '[class WallpaperController]'
module.exports = WallpaperController
